
from urllib import quote_plus
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import users

from VizSpread.appengine_utilities import sessions
from VizSpread.appengine import models as vizmodels
from VizSpread.appengine.contactsparser import ContactsParser
from VizSpread import GMAPS_API_KEY, GMAPS_GEOCODE_SERVICE_URL

class ContactsLoader():
	"""
	A class to retrieve a dataset of contacts data from the datastore and
	load it up so that it can be used by Google's maps API
	"""
	def __init__(self, dataSetName):
		self.dataSetName = dataSetName
		self.dataCentre = ''
		self.contactsData = ''
		#self.dataHeaders = ''
		self.contacts = []
	
	def getHtmlTableHeaderRow(self, headers):
		headerNum = 0
		tableRow = '<tr>\n'
		for header in headers:
			tableRow += '<th>%s</th>' % header
			headerNum = headerNum + 1
		tableRow += '</tr>\n'
		return tableRow
		
	def loadDataset(self):
		loadSuccess = True
		user = users.get_current_user()
		session = sessions.Session()

		try:
			sets = session['sets']
		except KeyError:
			sets = []

		if user == None:		
			datasets = []
			for sessId in sets:
				query = "SELECT * FROM Dataset WHERE name = '%s' AND sessionId = '%s'" % (self.dataSetName, sessId)
				gqlquery = db.GqlQuery(query)
				results = gqlquery.fetch(1)
				if len(results) == 1:
					continue
		else:
			query = "SELECT * FROM Dataset WHERE WHERE name = '%s' AND owner = '%s'" % (self.dataSetName, user)
		
		results = db.GqlQuery(query)

		try:
			dataset = results[0]
			self.dataCentre = dataset.dataCentre
			self.contactsData = dataset.dataCSV
			#parser = ContactsParser(self.dataSetName, self.dataCentre, self.contactsData)
			#field_headers = parser.getFieldHeaders()
			#field_header_positions = parser.getFieldHeaderPositions(field_headers)
			self.contacts = db.GqlQuery("SELECT * FROM Contact WHERE set = :set", set=dataset)
		except IndexError:
			loadSuccess = False
		
		return loadSuccess	
			
	def getGeodata(self):

		geocodeJSONObjectsList = []
		geocodeErrorsList = []

		for contact in self.contacts:
			jsonOb = eval(contact.geocodeResultJsonOb)
			if jsonOb["Status"]["code"] == 200:
				geocodeJSONObjectsList.append(contact.geocodeResultJsonOb)
			else:
				geocodeErrorsList.append(jsonOb["name"])

		geodataString = ",".join(geocodeJSONObjectsList)
		geocodeErrorsString = ",".join(geocodeErrorsList)
		
		return [geodataString, geocodeErrorsString]

	def getContactsHtmlTable(self):
		"""
		returns the addresses formatted in the hCard microformat in an HTML table
		"""
		html = '<table id="contacts" border="1">\n'
		contactsList = self.contactsData.split('\n')
		reader = csv.reader(contactsList)

		for row in reader:
			
			if reader.line_num == 1: # retrieve the headers
				headers = row
				headersRow = self.getHtmlTableHeaderRow(headers)
				html += headersRow
				continue

			fieldNum = 0
			tableRow = '<tr class="vcard">\n'
			for data in row:
				hcard_class=""
				if fieldNum == self.field_header_positions['fn']:
					hcard_class = 'fn'
				if fieldNum == self.field_header_positions['email']:
					hcard_class = 'email'
				if fieldNum == self.field_header_positions['street-address']:
					hcard_class = 'street-address'
				if fieldNum == self.field_header_positions['locality']:
					hcard_class = 'locality'
				if fieldNum == self.field_header_positions['region']:
					hcard_class = 'region'
				if fieldNum == self.field_header_positions['postal-code']:
					hcard_class = 'postal-code'
				if fieldNum == self.field_header_positions['country-name']:
					hcard_class = 'country-name'
				
				if data == '':
					data = '&nbsp;'
				tableRow += '<td class="%s">%s</td>\n' % (hcard_class, data)
				fieldNum = fieldNum + 1
			
			tableRow += '</tr>\n' 
			html += tableRow
			
		html += '</table>\n'

		return html
